<?php
/**
 * 后台志愿者申请管理API
 * 支持志愿者申请的查看、审核、状态管理等功能
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit;
}

// 数据库配置
$dbConfig = [
    'host' => 'localhost',
    'name' => 'nzy_congqian_cn', 
    'user' => 'nzy_congqian_cn',
    'pass' => 'FsnXrDfDhm4wFJSX',
    'charset' => 'utf8mb4'
];

// 数据库连接
try {
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['name']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['user'], $dbConfig['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    jsonResponse([
        'success' => false,
        'message' => '数据库连接失败: ' . $e->getMessage()
    ]);
}

// 响应函数
function jsonResponse($data) {
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function success($data = null, $message = '操作成功') {
    jsonResponse([
        'code' => 200,
        'success' => true,
        'message' => $message,
        'data' => $data,
        'timestamp' => time()
    ]);
}

function error($message = '操作失败', $code = 400) {
    jsonResponse([
        'code' => $code,
        'success' => false,
        'message' => $message,
        'data' => null,
        'timestamp' => time()
    ]);
}

// 简单的token验证
function verifyAdminToken($token) {
    global $pdo;
    
    if (empty($token)) {
        return false;
    }
    
    // 移除Bearer前缀
    if (strpos($token, 'Bearer ') === 0) {
        $token = substr($token, 7);
    }
    
    try {
        $sql = "SELECT au.*, ar.permissions 
                FROM admin_users au 
                LEFT JOIN admin_roles ar ON au.role_id = ar.id 
                WHERE au.id = ? AND au.status = 'active'";
        $stmt = $pdo->prepare($sql);
        // 简化token验证，实际应该有更复杂的验证逻辑
        $stmt->execute([1]); // 临时使用admin用户
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        return false;
    }
}

// 获取认证token
function getAuthToken() {
    $headers = getallheaders();
    $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    
    if (strpos($authHeader, 'Bearer ') === 0) {
        return substr($authHeader, 7);
    }
    
    return $_GET['token'] ?? $_POST['token'] ?? '';
}

// 验证管理员权限
$token = getAuthToken();
$admin = verifyAdminToken($token);

if (!$admin) {
    error('未授权的访问', 401);
}

// 获取志愿者申请列表
function getVolunteerList() {
    global $pdo;
    
    try {
        $page = max(1, (int)($_GET['page'] ?? 1));
        $limit = min(50, max(10, (int)($_GET['limit'] ?? 20)));
        $offset = ($page - 1) * $limit;
        
        // 构建查询条件
        $where = "1=1";
        $params = [];
        
        // 状态筛选
        if (isset($_GET['status']) && $_GET['status'] !== '') {
            $where .= " AND va.status = ?";
            $params[] = $_GET['status'];
        }
        
        // 性别筛选
        if (isset($_GET['gender']) && !empty($_GET['gender'])) {
            $where .= " AND va.gender = ?";
            $params[] = $_GET['gender'];
        }
        
        // 院系筛选
        if (isset($_GET['department']) && !empty($_GET['department'])) {
            $where .= " AND va.department LIKE ?";
            $params[] = '%' . $_GET['department'] . '%';
        }
        
        // 关键词搜索
        if (isset($_GET['search']) && !empty($_GET['search'])) {
            $where .= " AND (va.name LIKE ? OR va.phone LIKE ? OR va.student_id LIKE ?)";
            $params[] = '%' . $_GET['search'] . '%';
            $params[] = '%' . $_GET['search'] . '%';
            $params[] = '%' . $_GET['search'] . '%';
        }
        
        // 查询总数
        $countSql = "SELECT COUNT(*) FROM volunteer_applications va WHERE $where";
        $countStmt = $pdo->prepare($countSql);
        $countStmt->execute($params);
        $total = $countStmt->fetchColumn();
        
        // 查询列表数据
        $sql = "SELECT 
                    va.id,
                    va.user_id,
                    va.name,
                    va.gender,
                    va.phone,
                    va.student_id,
                    va.department,
                    va.grade,
                    va.experience,
                    va.available_time,
                    va.self_introduction,
                    va.status,
                    va.review_note,
                    va.created_at,
                    va.updated_at,
                    u.nickname as user_nickname,
                    u.real_name as user_real_name,
                    u.avatar as user_avatar
                FROM volunteer_applications va
                LEFT JOIN users u ON va.user_id = u.id
                WHERE $where
                ORDER BY va.created_at DESC
                LIMIT ? OFFSET ?";
        
        // 将 LIMIT 和 OFFSET 作为整数绑定
        $stmt = $pdo->prepare($sql);
        
        // 绑定前面的查询参数
        for($i = 0; $i < count($params); $i++) {
            $stmt->bindValue($i + 1, $params[$i]);
        }
        
        // 绑定 LIMIT 和 OFFSET 参数为整数
        $stmt->bindValue(count($params) + 1, (int)$limit, PDO::PARAM_INT);
        $stmt->bindValue(count($params) + 2, (int)$offset, PDO::PARAM_INT);
        
        $stmt->execute();
        $applications = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 格式化数据
        foreach ($applications as &$app) {
            // 格式化状态
            $statusMap = [
                0 => '待审核',
                1 => '已通过', 
                2 => '已拒绝'
            ];
            $app['status_text'] = $statusMap[$app['status']] ?? '未知';
            
            // 格式化性别
            $app['gender_text'] = $app['gender'] == 'male' ? '男' : '女';
            
            // 用户信息
            $app['user_name'] = $app['user_real_name'] ?: $app['user_nickname'] ?: '未知用户';
        }
        
        success([
            'list' => $applications,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => (int)$total,
                'pages' => ceil($total / $limit)
            ]
        ]);
        
    } catch (Exception $e) {
        error('获取申请列表失败: ' . $e->getMessage(), 500);
    }
}

// 获取志愿者申请详情
function getVolunteerDetail() {
    global $pdo;
    
    $id = $_GET['id'] ?? 0;
    if (!$id) {
        error('缺少申请ID');
    }
    
    try {
        $sql = "SELECT 
                    va.*,
                    u.nickname as user_nickname,
                    u.real_name as user_real_name,
                    u.phone as user_phone,
                    u.avatar as user_avatar
                FROM volunteer_applications va
                LEFT JOIN users u ON va.user_id = u.id
                WHERE va.id = ?";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id]);
        $application = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$application) {
            error('申请不存在');
        }
        
        // 格式化状态
        $statusMap = [
            0 => '待审核',
            1 => '已通过', 
            2 => '已拒绝'
        ];
        $application['status_text'] = $statusMap[$application['status']] ?? '未知';
        
        // 格式化性别
        $application['gender_text'] = $application['gender'] == 'male' ? '男' : '女';
        
        // 用户信息
        $application['user_name'] = $application['user_real_name'] ?: $application['user_nickname'] ?: '未知用户';
        
        success($application);
        
    } catch (Exception $e) {
        error('获取申请详情失败: ' . $e->getMessage(), 500);
    }
}

// 审核志愿者申请
function reviewVolunteer() {
    global $pdo, $admin;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $id = $input['id'] ?? 0;
    $status = $input['status'] ?? '';
    $reviewNote = trim($input['review_note'] ?? '');
    
    if (!$id) {
        error('缺少申请ID');
    }
    
    if (!in_array($status, ['1', '2', 1, 2])) {
        error('无效的审核状态');
    }
    
    $status = (int)$status;
    
    try {
        $pdo->beginTransaction();
        
        // 获取申请信息
        $appSql = "SELECT name, user_id FROM volunteer_applications WHERE id = ?";
        $appStmt = $pdo->prepare($appSql);
        $appStmt->execute([$id]);
        $app = $appStmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$app) {
            throw new Exception('申请不存在');
        }
        
        // 更新申请状态
        $sql = "UPDATE volunteer_applications SET 
                    status = ?, 
                    review_note = ?,
                    updated_at = NOW() 
                WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$status, $reviewNote, $id]);
        
        // 如果通过申请，将申请人信息自动保存到常用观众信息
        if ($status == 1) {
            $saveVisitorSql = "INSERT INTO common_visitors (user_id, name, phone, created_at, updated_at) 
                              SELECT ?, ?, ?, NOW(), NOW()
                              FROM volunteer_applications 
                              WHERE id = ? AND NOT EXISTS (
                                  SELECT 1 FROM common_visitors 
                                  WHERE user_id = ? AND name = ?
                              )";
            $saveVisitorStmt = $pdo->prepare($saveVisitorSql);
            $saveVisitorStmt->execute([
                $app['user_id'], 
                $app['name'], 
                $input['phone'] ?? '', 
                $id, 
                $app['user_id'], 
                $app['name']
            ]);
        }
        
        // 记录操作日志
        $statusText = $status == 1 ? '已通过' : '已拒绝';
        $logSql = "INSERT INTO admin_operation_logs 
                   (admin_id, username, action, module, description, ip_address, user_agent, created_at) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
        $logStmt = $pdo->prepare($logSql);
        $logStmt->execute([
            $admin['id'],
            $admin['username'],
            '志愿者申请审核',
            'volunteer',
            "审核志愿者申请「{$app['name']}」为：{$statusText}" . ($reviewNote ? "，备注：{$reviewNote}" : ''),
            $_SERVER['REMOTE_ADDR'] ?? '',
            $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);
        
        $pdo->commit();
        success(null, '审核成功');
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error('审核失败: ' . $e->getMessage(), 500);
    }
}

// 删除志愿者申请
function deleteVolunteer() {
    global $pdo, $admin;
    
    $id = $_GET['id'] ?? 0;
    if (!$id) {
        error('缺少申请ID');
    }
    
    try {
        $pdo->beginTransaction();
        
        // 先获取申请信息用于日志
        $appSql = "SELECT name FROM volunteer_applications WHERE id = ?";
        $appStmt = $pdo->prepare($appSql);
        $appStmt->execute([$id]);
        $app = $appStmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$app) {
            throw new Exception('申请不存在');
        }
        
        // 删除申请
        $sql = "DELETE FROM volunteer_applications WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id]);
        
        // 记录操作日志
        $logSql = "INSERT INTO admin_operation_logs 
                   (admin_id, username, action, module, description, ip_address, user_agent, created_at) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
        $logStmt = $pdo->prepare($logSql);
        $logStmt->execute([
            $admin['id'],
            $admin['username'],
            '删除志愿者申请',
            'volunteer',
            "删除了志愿者申请：「{$app['name']}」",
            $_SERVER['REMOTE_ADDR'] ?? '',
            $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);
        
        $pdo->commit();
        success(null, '删除成功');
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error('删除失败: ' . $e->getMessage(), 500);
    }
}

// 获取志愿者申请统计
function getVolunteerStats() {
    global $pdo;
    
    try {
        // 总体统计
        $totalSql = "SELECT 
                        COUNT(*) as total,
                        COUNT(CASE WHEN status = 0 THEN 1 END) as pending_count,
                        COUNT(CASE WHEN status = 1 THEN 1 END) as approved_count,
                        COUNT(CASE WHEN status = 2 THEN 1 END) as rejected_count
                     FROM volunteer_applications";
        $totalStmt = $pdo->query($totalSql);
        $totalStats = $totalStmt->fetch(PDO::FETCH_ASSOC);
        
        // 按院系统计
        $deptSql = "SELECT 
                        department,
                        COUNT(*) as count
                    FROM volunteer_applications 
                    WHERE department IS NOT NULL AND department != ''
                    GROUP BY department 
                    ORDER BY count DESC
                    LIMIT 10";
        $deptStmt = $pdo->query($deptSql);
        $deptStats = $deptStmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 按性别统计
        $genderSql = "SELECT 
                        gender,
                        COUNT(*) as count
                      FROM volunteer_applications 
                      GROUP BY gender";
        $genderStmt = $pdo->query($genderSql);
        $genderStats = $genderStmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 最近7天统计
        $recentSql = "SELECT 
                        DATE(created_at) as date,
                        COUNT(*) as count
                      FROM volunteer_applications 
                      WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
                      GROUP BY DATE(created_at)
                      ORDER BY date DESC";
        $recentStmt = $pdo->query($recentSql);
        $recentStats = $recentStmt->fetchAll(PDO::FETCH_ASSOC);
        
        success([
            'total_stats' => $totalStats,
            'department_stats' => $deptStats,
            'gender_stats' => $genderStats,
            'recent_stats' => $recentStats
        ]);
        
    } catch (Exception $e) {
        error('获取统计信息失败: ' . $e->getMessage(), 500);
    }
}

// 获取院系列表（用于筛选下拉框）
function getDepartments() {
    global $pdo;
    
    try {
        $sql = "SELECT DISTINCT department 
                FROM volunteer_applications 
                WHERE department IS NOT NULL AND department != ''
                ORDER BY department";
        $stmt = $pdo->query($sql);
        $departments = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
        success($departments);
        
    } catch (Exception $e) {
        error('获取院系列表失败: ' . $e->getMessage(), 500);
    }
}

// 批量审核
function batchReview() {
    global $pdo, $admin;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $ids = $input['ids'] ?? [];
    $status = $input['status'] ?? '';
    $reviewNote = trim($input['review_note'] ?? '');
    
    if (empty($ids) || !is_array($ids)) {
        error('请选择要审核的申请');
    }
    
    if (!in_array($status, ['1', '2', 1, 2])) {
        error('无效的审核状态');
    }
    
    $status = (int)$status;
    
    try {
        $pdo->beginTransaction();
        
        $successCount = 0;
        $placeholders = str_repeat('?,', count($ids) - 1) . '?';
        
        // 获取申请信息
        $appSql = "SELECT id, name, user_id FROM volunteer_applications WHERE id IN ($placeholders)";
        $appStmt = $pdo->prepare($appSql);
        $appStmt->execute($ids);
        $apps = $appStmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 批量更新状态
        $sql = "UPDATE volunteer_applications SET 
                    status = ?, 
                    review_note = ?,
                    updated_at = NOW() 
                WHERE id IN ($placeholders)";
        $params = array_merge([$status, $reviewNote], $ids);
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $successCount = $stmt->rowCount();
        
        // 如果是通过状态，批量保存到常用观众信息
        if ($status == 1) {
            foreach ($apps as $app) {
                $saveVisitorSql = "INSERT INTO common_visitors (user_id, name, phone, created_at, updated_at) 
                                  VALUES (?, ?, '', NOW(), NOW())
                                  ON DUPLICATE KEY UPDATE updated_at = NOW()";
                $saveVisitorStmt = $pdo->prepare($saveVisitorSql);
                $saveVisitorStmt->execute([$app['user_id'], $app['name']]);
            }
        }
        
        // 记录操作日志
        $statusText = $status == 1 ? '已通过' : '已拒绝';
        $logSql = "INSERT INTO admin_operation_logs 
                   (admin_id, username, action, module, description, ip_address, user_agent, created_at) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
        $logStmt = $pdo->prepare($logSql);
        $logStmt->execute([
            $admin['id'],
            $admin['username'],
            '批量审核志愿者申请',
            'volunteer',
            "批量审核了{$successCount}个志愿者申请为：{$statusText}",
            $_SERVER['REMOTE_ADDR'] ?? '',
            $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);
        
        $pdo->commit();
        success(['success_count' => $successCount], "成功审核{$successCount}个申请");
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error('批量审核失败: ' . $e->getMessage(), 500);
    }
}

// 处理请求
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            switch ($action) {
                case 'list':
                    getVolunteerList();
                    break;
                case 'detail':
                    getVolunteerDetail();
                    break;
                case 'stats':
                    getVolunteerStats();
                    break;
                case 'departments':
                    getDepartments();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        case 'POST':
            switch ($action) {
                case 'review':
                    reviewVolunteer();
                    break;
                case 'batch_review':
                    batchReview();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        case 'DELETE':
            deleteVolunteer();
            break;
            
        default:
            error('不支持的请求方法');
    }
    
} catch (PDOException $e) {
    error('数据库错误: ' . $e->getMessage(), 500);
} catch (Exception $e) {
    error('服务器错误: ' . $e->getMessage(), 500);
}
?>